package com.xiezc.controller

import com.xiezc.util.HeaderInterceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.ResponseBody
import java.io.IOException
import java.nio.charset.Charset


/**
 * @author wb-xzc291800
 * @date 2017/11/01 11:15
 */
class GetHTML {
    private val client = OkHttpClient().newBuilder().addInterceptor(HeaderInterceptor()).build()

    private val defaultCharset = Charset.forName("utf8")
    /**
     * get方法获得页面
     */
    fun getHTMLStr(url: String): String? {
        val request = Request.Builder().url(url).build()
        val response = client.newCall(request).execute()
        if (response.isSuccessful) {
            val responseBody = response.body()
            return if (responseBody != null) findStr(responseBody) else null
        } else {
            throw IOException("Unexpected code " + response)
        }
    }


    fun postHTMLStr(){

    }


    /**
     * 从responseBody中获得正确编码的网页String
     */
    private fun findStr(responseBody: ResponseBody): String {
        val byteArray = responseBody.bytes()
        var str = String(byteArray, defaultCharset)
        var charset = responseBody.contentType()?.charset()
        if (charset == null) {
            charset = findCharset(str)
        }
        if (defaultCharset != charset) {
            str = String(byteArray, charset)
        }
        return str
    }

    private fun findCharset(body: String): Charset {
        val charsetReg1 = """<meta[ ]+http-equiv=["']?content-type|Content-Type["']?[ ]+content=["']?text/html;[ ]*charset=([0-9-a-zA-Z]+)["']?"""
        val charsetReg2 = """<meta[ ]+charset=["']?([0-9-a-zA-Z]+)["']?[ ]+"""
        //使用kotlin方法打印出匹配出的内容
        var charsetStr = Regex(charsetReg1)
                .findAll(body)
                .toList()
                .flatMap(MatchResult::groupValues)
                .lastOrNull()
        if (charsetStr == null) {
            charsetStr = Regex(charsetReg2)
                    .findAll(body)
                    .toList()
                    .flatMap(MatchResult::groupValues).lastOrNull()
        }
        return if (charsetStr == null) defaultCharset else Charset.forName(charsetStr)
    }

}

